<?php

namespace app\services;

use plugin\admin\app\model\Coupon;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserCoupon;

class VIPService
{
    public static function config()
    {
        $config = ConfigService::get('site');

        return $config;
    }

    public static function toVip($userId)
    {
        $config = self::config();

        $userInfo = User::find($userId);

        if ($userInfo['is_vip']) {
            $userInfo['expiry_time'] = strtotime('+1 year', $userInfo['expiry_time']);
        } else {
            $userInfo['is_vip'] = 1;
            $userInfo['expiry_time'] = strtotime('+1 year');
        }

        $userInfo['vip_off'] = $config['vip_off'];
        $userInfo->save();

        $coupons = Coupon::all();

        $data = [];
        foreach ($coupons as $coupon) {
            $data[] = [
                'user_id' => get_user_id(),
                'coupon_id' => $coupon['id'],
                'data' => json_encode($coupon, JSON_UNESCAPED_UNICODE),
                'created_time' => time(),
                'expiry_time' => strtotime('+' . $coupon['expiry_days'] . ' days'),
            ];
        }

        Coupon::where('id', '>', 0)->increment('count', 1);

        UserCoupon::insert($data);
    }
}